﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Data.SqlClient;
using System.Windows.Shapes;
using System.Windows.Media;

namespace 餐饮管理系统
{
    public partial class MainWindow : Window
    {
        private void loadDateSelected()
        {
            ListBoxItem dateListBoxItem = DingdanListBox.SelectedItem as ListBoxItem;

            if (dateListBoxItem == null)
                return;

            Int64[] id = new Int64[1000];
            DateTime[] time = new DateTime[1000];
            int[] tableNum = new int[1000];

            int[] yearMonthDay = dateSpliter(dateListBoxItem.Content.ToString().Trim());
            DateTime timeNeed = new DateTime(yearMonthDay[0], yearMonthDay[1], yearMonthDay[2]);

            string branchName = getBranchName();
            if (branchName == null)
            {
                return;
            }
            string command = "select * from OrderTable where DATEDIFF ( day , time , '" 
                + timeNeed + "' ) = 0"
                + " and branch_name = '" + branchName + "'";
            listOrders(command);

        }

        private void loadOnlineDateSelected()
        {
            ListBoxItem dateListBoxItem = DingdanListBox.SelectedItem as ListBoxItem;

            if (dateListBoxItem == null)
                return;

            Int64[] id = new Int64[1000];
            DateTime[] time = new DateTime[1000];
            int[] tableNum = new int[1000];

            int[] yearMonthDay = dateSpliter(dateListBoxItem.Content.ToString().Trim());
            DateTime timeNeed = new DateTime(yearMonthDay[0], yearMonthDay[1], yearMonthDay[2]);

            string branchName = getBranchName();
            if (branchName == null)
            {
                return;
            }
            string command = "select * from OnlineOrderTable where DATEDIFF ( day , time , '"
                + timeNeed + "' ) = 0"
                + " and branch_name = '" + branchName + "'";
            listOnlineOrders(command);

        }

        private void listOrders(string command)
        {
            DingdanContentListBox.Items.Clear();

            Int64[] id = new Int64[1000];
            DateTime[] time = new DateTime[1000];
            int[] tableNum = new int[1000];
            bool[] served = new bool[1000];

            string sql = command;
            SqlDataReader dataReader = databaseConnect.GetDataReader(sql);
            for (int i = 0; dataReader.Read(); i++)
            {

                id[i] = (Int64)dataReader[0];
                tableNum[i] = (int)dataReader[1];
                time[i] = (DateTime)dataReader[2];
                served[i] = (bool)dataReader[4];
            }
            dataReader.Close();

            for (int i = 0; id[i] != 0; i++)
            {
                ListBoxItem item = new ListBoxItem();
                item.SetResourceReference(ListBoxItem.StyleProperty, "ReserverBoxItem");
                item.ApplyTemplate();
                Label timeLbl = item.Template.FindName("time", item) as Label;
                Label idLbl = item.Template.FindName("id", item) as Label;
                Label tPLbl = item.Template.FindName("totalPrice", item) as Label;
                ListBox priceLb = item.Template.FindName("price", item) as ListBox;
                Button tableNumBtn = item.Template.FindName("controlbutton", item) as Button;
                tableNumBtn.SetResourceReference(Button.StyleProperty, "ControlButton");
                
                timeLbl.Content = time[i].Hour.ToString() + ":" + formatMinute(time[i].Minute) ;
                idLbl.Content = id[i].ToString();
                tableNumBtn.Content = tableNum[i].ToString();
                priceLb.Items.Clear();

                tableNumBtn.ApplyTemplate();
                if (served[i] == true)
                {
                    Rectangle colorRect = tableNumBtn.Template.FindName("numberOfTable", tableNumBtn) as Rectangle;
                    SolidColorBrush mySolidColorBrush = new SolidColorBrush();

                    mySolidColorBrush.Color = Color.FromRgb(0, 255, 0);
                    colorRect.Fill = mySolidColorBrush;
                }

                priceSum = 0;
                string sqlMeal = "select * from OrderMeal where order_id = " + id[i];
                SqlDataReader dataReaderMeal = databaseConnect.GetDataReader(sqlMeal);
                while (dataReaderMeal.Read())
                {
                    ListBoxItem lbi = new ListBoxItem();
                    lbi.Content = "菜名: " + (meal[(Int64)dataReaderMeal[1]]).ToString();
                    if (dataReaderMeal[2] != null && !dataReaderMeal[2].ToString().Equals(""))
                    {
                        lbi.Content += " × " + (int)dataReaderMeal[2];
                        priceSum += (mealPrice[(Int64)dataReaderMeal[1]] * (int)dataReaderMeal[2]);
                    }
                    else
                    {
                        lbi.Content += " × 1";
                        priceSum += mealPrice[(Int64)dataReaderMeal[1]];
                    }
                    priceLb.Items.Add(lbi);
                }
                tPLbl.Content = priceSum.ToString();
                dataReaderMeal.Close();
                DingdanContentListBox.Items.Add(item);
            }

            this.tableNum.Clear();
        }

        private void listOnlineOrders(string command)
        {
            DingdanWebContentListBox.Items.Clear();

            Int64[] id = new Int64[1000];
            DateTime[] time = new DateTime[1000];
            string[] location = new string[1000];
            bool[] served = new bool[1000];

            string sql = command;
            SqlDataReader dataReader = databaseConnect.GetDataReader(sql);
            for (int i = 0; dataReader.Read(); i++)
            {

                id[i] = (Int64)dataReader[0];
                location[i] = dataReader[1].ToString().Trim();
                time[i] = (DateTime)dataReader[2];
                served[i] = (bool)dataReader[3];
            }
            dataReader.Close();

            for (int i = 0; id[i] != 0; i++)
            {
                ListBoxItem item = new ListBoxItem();
                item.SetResourceReference(ListBoxItem.StyleProperty, "OnlineReserverItem");
                item.ApplyTemplate();
                Label timeLbl = item.Template.FindName("time", item) as Label;
                Label idLbl = item.Template.FindName("id", item) as Label;
                Label tPLbl = item.Template.FindName("totalPrice", item) as Label;
                Label addrLbl = item.Template.FindName("address", item) as Label;
                ListBox priceLb = item.Template.FindName("price", item) as ListBox;
                Button tableNumBtn = item.Template.FindName("controlbutton", item) as Button;
                tableNumBtn.SetResourceReference(Button.StyleProperty, "OnlineBtn");
                tableNumBtn.ApplyTemplate();

                timeLbl.Content = time[i].Hour.ToString() + ":" + formatMinute(time[i].Minute);
                idLbl.Content = id[i].ToString();
                addrLbl.Content = location[i];
                //tableNumBtn.Content = tableNum[i].ToString();


                if (served[i] == true)
                {
                    Rectangle colorRect = tableNumBtn.Template.FindName("numberOfTable", tableNumBtn) as Rectangle;
                    SolidColorBrush mySolidColorBrush = new SolidColorBrush();

                    mySolidColorBrush.Color = Color.FromRgb(0, 255, 0);
                    colorRect.Fill = mySolidColorBrush;
                }

                //priceLb.Items.Clear();
                priceSum = 0;
                string sqlMeal = "select * from OnlineOrderMeal where order_id = " + id[i];
                SqlDataReader dataReaderMeal = databaseConnect.GetDataReader(sqlMeal);
                while (dataReaderMeal.Read())
                {
                    ListBoxItem lbi = new ListBoxItem();
                    lbi.Content = "菜名: " + (meal[(Int64)dataReaderMeal[1]]).ToString();
                    if (dataReaderMeal[2] != null && !dataReaderMeal[2].ToString().Equals(""))
                    {
                        lbi.Content += " × " + (int)dataReaderMeal[2];
                        priceSum += (mealPrice[(Int64)dataReaderMeal[1]] * (int)dataReaderMeal[2]);
                    }
                    else
                    {
                        lbi.Content += " × 1";
                        priceSum += mealPrice[(Int64)dataReaderMeal[1]];
                    }
                    priceLb.Items.Add(lbi);
                }
                tPLbl.Content = priceSum.ToString();
                dataReaderMeal.Close();
                DingdanWebContentListBox.Items.Add(item);
            }
        }


        private void updateOrder()
        {
            DateTime timeNow = DateTime.Now;

            int tableNum = int.Parse(this.tableNum.Text);

            string itemName = this.itemName.Text.Trim();

            Int64 id = 0;
            string sql = "select max(id) from OrderTable";
            SqlDataReader dataReader = databaseConnect.GetDataReader(sql);
            while (dataReader.Read())
            {
                id = (Int64)dataReader[0];
            }
            dataReader.Close();



            ListBoxItem item = new ListBoxItem();
            item.SetResourceReference(ListBoxItem.StyleProperty, "ReserverBoxItem");
            item.ApplyTemplate();
            Label timeLbl = item.Template.FindName("time", item) as Label;
            Label idLbl = item.Template.FindName("id", item) as Label;
            Label tPLbl = item.Template.FindName("totalPrice", item) as Label;
            ListBox priceLb = item.Template.FindName("price", item) as ListBox;
            Button tableNumBtn = item.Template.FindName("controlbutton", item) as Button;

            timeLbl.Content = timeNow.Hour.ToString() + ":" + formatMinute(timeNow.Minute);
            idLbl.Content = (id + 1).ToString();
            tableNumBtn.Content = tableNum.ToString();


            //string sqlMeal = "select * from OrderMeal where order_id = " + id[0];
            //SqlDataReader dataReaderMeal = databaseConnect.GetDataReader(sqlMeal);
            //while (dataReaderMeal.Read())
            //{
            //    ListBoxItem lbi = new ListBoxItem();
            //    lbi.Content += "菜名: " + (meal[(Int64)dataReaderMeal[0]]).ToString();
            //    priceLb.Items.Add(lbi);
            //}

            //dataReaderMeal.Close();


            //ListBoxItem item = new ListBoxItem();
            //item.SetResourceReference(ListBoxItem.StyleProperty, "OrderListBoxItem");
            //item.Content = "订单号: " + (id + 1).ToString()
            //                    + "时间: " + timeNow.ToString()
            //                    + "桌号: " + tableNum.ToString() + " ";

            string branchName = getBranchName();
            if (branchName == null)
            {
                return;
            }
            sql = "insert into OrderTable(table_number,time,branch_name) values ("
                    + tableNum + ",'"
                    + timeNow + "','" 
                    + branchName + "')"; 

            databaseConnect.ExecuteQuery(sql);


            //这里加循环
            priceSum = 0;
            foreach (int tempMealNum in mealInOrder)
            {
                int tempMealCount = mealCountInOrder.ElementAt(mealInOrder.IndexOf(tempMealNum));

                sql = "insert into OrderMeal values ("
                    + (id + 1) + ","
                    + tempMealNum + ","
                    + tempMealCount + ")";
                databaseConnect.ExecuteQuery(sql);


                ListBoxItem lbi = new ListBoxItem();
                lbi.Content = "菜名: " + (meal[tempMealNum]).ToString() + " × " + tempMealCount;
                priceSum += (mealPrice[tempMealNum] * tempMealCount);
                priceLb.Items.Add(lbi);
            }
            tPLbl.Content = priceSum.ToString();
            DingdanContentListBox.Items.Add(item);

            DingdanAddListBox.Items.Clear();
            mealInOrder.Clear();
            mealCountInOrder.Clear();




            ListBoxItem dayListBoxItem = new ListBoxItem();
            dayListBoxItem.SetResourceReference(ListBoxItem.StyleProperty, "ListBoxItemStyle1");
            dayListBoxItem.ApplyTemplate();
            dayListBoxItem.Content = timeNow.Year + "-"
                             + timeNow.Month + "-"
                             + timeNow.Day;

            bool unique = true;
            foreach (ListBoxItem lbi in DingdanListBox.Items)
            {
                if (lbi.Content.Equals(dayListBoxItem.Content))
                {
                    unique = false;
                }
            }
            if (unique)
            {
                DingdanListBox.Items.Add(dayListBoxItem);
            }
        }




        private void initOrder()
        {
            DingdanListBox.Items.Clear();
            DingdanContentListBox.Items.Clear();
            DingdanAddListBox.Items.Clear();
            mealInOrder.Clear();
            mealCountInOrder.Clear();

            string sql = "select * from MealTable";
            SqlDataReader dataReader = databaseConnect.GetDataReader(sql);
            while (dataReader.Read())
            {
                meal[(Int64)dataReader[0]] = dataReader[1].ToString().Trim();
                mealPrice[(Int64)dataReader[0]] = float.Parse(dataReader[2].ToString());
            }
            dataReader.Close();
            listDate();
            listOnlineDate();
        }
        string[] meal = new string[1000];
        float[] mealPrice = new float[1000];
        float priceSum = 0;

        private int[] dateSpliter(string content)
        {
            string[] date = content.Split('-');
            int[] yearMonthDay = new int[3];
            yearMonthDay[0] = int.Parse(date[0]);
            yearMonthDay[1] = int.Parse(date[1]);
            yearMonthDay[2] = int.Parse(date[2]);
            return yearMonthDay;
        }



        private void listDate()
        {
            DingdanListBox.Items.Clear();
            DateTime latestDay = new DateTime();
            string branchName = getBranchName();
            if (branchName == null)
            {
                return;
            }
            string sqlList = "select * from OrderTable"
                           + " where branch_name = '" + branchName + "'";
            SqlDataReader dataReaderList = databaseConnect.GetDataReader(sqlList);
            while (dataReaderList.Read())
            {
                ListBoxItem item = new ListBoxItem();
                item.SetResourceReference(ListBoxItem.StyleProperty, "ListBoxItemStyle1");
                item.ApplyTemplate();
                item.Content = ((DateTime)dataReaderList[2]).Year + "-"
                             + ((DateTime)dataReaderList[2]).Month + "-"
                             + ((DateTime)dataReaderList[2]).Day;

                bool unique = true;
                foreach (ListBoxItem lbi in DingdanListBox.Items)
                {
                    if (lbi.Content.Equals(item.Content))
                    {
                        unique = false;
                        break;
                    }
                }
                if (unique)
                {
                    DingdanListBox.Items.Add(item);
                    latestDay = ((DateTime)dataReaderList[2]);
                }
            }
            dataReaderList.Close();

            if (latestDay.Year == 1)
            {
                return;
            }
            if (DingdanListBox.Items.Count > 0)
            (DingdanListBox.Items[DingdanListBox.Items.Count - 1] as ListBoxItem).IsSelected = true;
            

            string command = "select * from OrderTable where DATEDIFF ( day , time , '" + latestDay + "' ) = 0";
            listOrders(command);

        }

        private void listOnlineDate()
        {
            WangshangDingdanListBox.Items.Clear();
            DateTime latestDay = new DateTime();
            string branchName = getBranchName();
            if (branchName == null)
            {
                return;
            }
            string sqlList = "select * from OnlineOrderTable"
                           + " where branch_name = '" + branchName + "'";
            SqlDataReader dataReaderList = databaseConnect.GetDataReader(sqlList);
            while (dataReaderList.Read())
            {
                ListBoxItem item = new ListBoxItem();
                item.SetResourceReference(ListBoxItem.StyleProperty, "ListBoxItemStyle1");
                item.ApplyTemplate();
                item.Content = ((DateTime)dataReaderList[2]).Year + "-"
                             + ((DateTime)dataReaderList[2]).Month + "-"
                             + ((DateTime)dataReaderList[2]).Day;

                bool unique = true;
                foreach (ListBoxItem lbi in WangshangDingdanListBox.Items)
                {
                    if (lbi.Content.Equals(item.Content))
                    {
                        unique = false;
                        break;
                    }
                }
                if (unique)
                {
                    WangshangDingdanListBox.Items.Add(item);
                    latestDay = ((DateTime)dataReaderList[2]);
                }
            }
            dataReaderList.Close();

            if (latestDay.Year == 1)
            {
                return;
            }
            if (WangshangDingdanListBox.Items.Count > 0)
                (WangshangDingdanListBox.Items[WangshangDingdanListBox.Items.Count - 1] as ListBoxItem).IsSelected = true;

            string command = "select * from OnlineOrderTable where DATEDIFF ( day , time , '" + latestDay + "' ) = 0";
            listOnlineOrders(command);

        }

        List<int> mealInOrder = new List<int>();
        List<int> mealCountInOrder = new List<int>();

        private void addMealEvent()
        {
            int number = int.Parse(mealNum.Text);
            int count = int.Parse(mealCount.Text);

            if (meal[number] == null || meal[number].Equals("") || number > 999)
            {
                MessageBox.Show("菜号不存在！");
                mealNum.Clear();
                return;
            }
            foreach(int i in mealInOrder)
            {
                if (i == number)
                {
                    MessageBox.Show("菜号重复！");
                    mealNum.Clear();
                    return;
                }
            }
            mealInOrder.Add(number);
            mealCountInOrder.Add(count);

            ListBoxItem item = new ListBoxItem();
            item.SetResourceReference(ListBoxItem.StyleProperty, "OrderListBoxItemStyle");
            item.ApplyTemplate();
            item.Content = meal[number] + " × " + count;

            DingdanAddListBox.Items.Add(item);

            mealNum.Clear();
            mealCount.Clear();
        }

        private void deleteMeal(object sender)
        {
            object itemName = (sender as Button).Content;
            foreach (ListBoxItem lbi in DingdanAddListBox.Items)
            {
                if (lbi.Content.Equals(itemName))
                {
                    int itemIndex = DingdanAddListBox.Items.IndexOf(lbi);
                    mealInOrder.RemoveAt(itemIndex);
                    mealCountInOrder.RemoveAt(itemIndex);
                    DingdanAddListBox.Items.Remove(lbi);
                    break;
                }
            }

        }
        private string getBranchName()
        {
            ListBoxItem branch = CenterListBox.SelectedItem as ListBoxItem;

            if (branch == null)
                return null;

            return branch.Content.ToString().Trim();
        }





        private void DingdanListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            loadDateSelected();
        }

        private void WangshangDingdanListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            loadOnlineDateSelected();
        }

        private void addOrder_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!orderTableNumRegex.IsMatch(tableNum.Text))
            {
                MessageBox.Show("桌号输入错误或输入太大！");
                tableNum.Clear();
                return;
            }
            if (DingdanAddListBox.Items.IsEmpty) return;
            updateOrder();
            tableNum.Clear();
        }

        private void addMeal_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!orderMenuNumRegex.IsMatch(mealNum.Text))
            {
                MessageBox.Show("菜号输入错误！");
                mealNum.Clear();
                return;
            }
            if (!orderMenuCountRegex.IsMatch(mealCount.Text) || int.Parse(mealCount.Text) == 0)
            {
                MessageBox.Show("数量输入错误或输入太大！");
                mealCount.Clear();
                return;
            }
            addMealEvent();
        }

        private void orderDeleteBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            deleteMeal(sender);
        }

        private string formatMinute(int minute)
        {
            if (minute < 10)
            {
                return "0" + minute.ToString();
            }
            else
            {
                return minute.ToString();
            }
        }
    }

    public partial class App : Application
    {

        private void controlbutton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            changeState(sender);
        }

        private void contentbuttonOnline_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            changeStateOnline(sender);
        }

        private void changeState(object sender)
        {
            Button stateBtn = sender as Button;
            //ListBoxItem stateLbi = null;

            MainWindow mainWindow = (this.MainWindow as MainWindow);

            ListBox list = mainWindow.DingdanContentListBox;

            
            for (int i = 0; i < list.Items.Count; i++) 
            {
                ListBoxItem it = list.Items.GetItemAt(i) as ListBoxItem;
                Button deliver = it.Template.FindName("controlbutton", it) as Button;
                deliver.SetResourceReference(Button.StyleProperty, "ControlButton");
                deliver.ApplyTemplate();
                if (stateBtn == deliver)
                {
                    Label idLbl = it.Template.FindName("id", it) as Label;
                    string sql = "update OrderTable set served = 1 where id = " + idLbl.Content;
                    mainWindow.DatabaseConnect.ExecuteQuery(sql);
                    break;
                }
            }


            Rectangle colorRect = stateBtn.Template.FindName("numberOfTable", stateBtn) as Rectangle;
            SolidColorBrush mySolidColorBrush = new SolidColorBrush();

            mySolidColorBrush.Color = Color.FromRgb(0, 255, 0);
            colorRect.Fill = mySolidColorBrush;

        }


        private void changeStateOnline(object sender)
        {
            Button stateBtn = sender as Button;
            //ListBoxItem stateLbi = null;

            MainWindow mainWindow = (this.MainWindow as MainWindow);

            ListBox list = mainWindow.DingdanWebContentListBox;


            for (int i = 0; i < list.Items.Count; i++)
            {
                ListBoxItem it = list.Items.GetItemAt(i) as ListBoxItem;

                Button deliver = it.Template.FindName("controlbutton", it) as Button;
                deliver.SetResourceReference(Button.StyleProperty, "ControlButton");
                deliver.ApplyTemplate();
                if (stateBtn == deliver)
                {
                    Label idLbl = it.Template.FindName("id", it) as Label;
                    string sql = "update OnlineOrderTable set served = 1 where id = " + idLbl.Content;
                    mainWindow.DatabaseConnect.ExecuteQuery(sql);
                    break;
                }
            }


            Rectangle colorRect = stateBtn.Template.FindName("numberOfTable", stateBtn) as Rectangle;
            SolidColorBrush mySolidColorBrush = new SolidColorBrush();

            mySolidColorBrush.Color = Color.FromRgb(0, 255, 0);
            colorRect.Fill = mySolidColorBrush;

        }
    }
}
